package com.lingkang.flychat.ui.activity.welcome;

import android.os.Bundle;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lingkang.flychat.R;
import com.lingkang.flychat.config.HandlerEnum;
import com.lingkang.flychat.dto.ResponseResult;
import com.lingkang.flychat.entity.User;
import com.lingkang.flychat.http.HttpUtils;
import com.lingkang.flychat.http.ResponseListenter;
import com.lingkang.flychat.http.service.UserService;
import com.lingkang.flychat.ui.activity.base.BaseActivity;
import com.lingkang.flychat.ui.activity.main.MainActivity;
import com.lingkang.flychat.ui.activity.test.TestActivity;
import com.orhanobut.hawk.Hawk;

public class WelcomeActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        initView();
    }

    private void initView() {
        String token = Hawk.get("token");
        if (StringUtils.isEmpty(token)) {
            toLogin();
        } else {
            long t = System.currentTimeMillis();
            long s = Hawk.get("loginTime");
            if (t - s > 1296000000) {
                //大于15天
                Hawk.put("token", null);
                toLogin();
            }
            //检查token
            HttpUtils.request(HttpUtils.createApi(UserService.class).info(), new ResponseListenter<ResponseResult<User>>() {
                @Override
                public void onSuccess(ResponseResult<User> data) {
                    if (data.getCode() != 0) {
                        Hawk.put("token", null);
                        if (data.getCode() == 2)
                            ToastUtils.showLong("身份已过期，请重新登录");
                        toLogin();
                        return;
                    }
                    Hawk.put("info", data.getData());
                    startIntent(MainActivity.class, true);
//                    startIntent(TestActivity.class,true);
                }

                @Override
                public void onFail(String data) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                    handler.sendEmptyMessage(HandlerEnum.toLogin.getWhat());
                }
            });
        }
    }

    private void toLogin() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.sendEmptyMessage(HandlerEnum.toLogin.getWhat());
            }
        }).start();
    }
}
